﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using DevComponents.DotNetBar.SuperGrid;
using DevComponents.DotNetBar.SuperGrid.Style;
using Platform.Model;
using Platform.Model.Repositories;
using PlatformManagement.Properties;

namespace PlatformManagement
{
    public partial class ArticleForm : DevComponents.DotNetBar.Metro.MetroForm
    {
	    private bool _currentRowDirty = false;

        public ArticleForm()
        {
            InitializeComponent();
	        dgvArticles.AutoGenerateColumns = false;
			
        }

        protected override void OnActivated(EventArgs e)
        {
            base.OnActivated(e);
            this.WindowState = FormWindowState.Maximized;
        }

        protected override void OnShown(EventArgs e)
        {
            // Thiet lap danh sach cac gia tri cho cot Cat
			clCat.DataSource = new[] { 1, 2, 3, 4 };
			clCat.FlatStyle = FlatStyle.Flat;

	        var bindingSource = new BindingSource { DataSource = WorkContext.Current.Articles.ToList() };
	        dgvArticles.DataSource = bindingSource;
			
			base.OnShown(e);
        }
		
        public void mnuDelete_Click(object sender, System.EventArgs e)
        {
			
        }

		private void mnuCopyTo_Click(object sender, EventArgs e)
		{
			
		}

	    private void dgvArticles_DataError(object sender, DataGridViewDataErrorEventArgs e)
		{
			
		}

		private void dgvArticles_RowValidated(object sender, DataGridViewCellEventArgs e)
		{
			if (_currentRowDirty)
			{
				try
				{
					// Lay dong hien tai
					var currentRow = dgvArticles.Rows[e.RowIndex];

					// Lay mat hang duoc hien thi tren dong hien tai
					var art = currentRow.DataBoundItem as Article;

					// cap nhat thoi gian va market id
					art.LastUpdated = DateTime.Now;
					art.MarketId = WorkSession.Current.Market.ID;

					// Goi ham them moi hoac cap nhat
					var id = WorkContext.Current.Articles.AddOrUpdate(art);

					// Gan lai id cua mat hang vao cot thu 2 cua gridview
					currentRow.Cells[1].Value = id;

					// Thoat khoi che do edit
					dgvArticles.CancelEdit();
				}
				catch (DuplicateNameException dne)
				{
					MessageBox.Show(dne.Message, "Error !", MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
				catch
				{
					MessageBox.Show(Resources.ArticleForm_sgArticle_RowValidating_Can_not_insert_new_article,
					                "Error !", MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
			}
			_currentRowDirty = false;
		}

		private void dgvArticles_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
		{
			if (dgvArticles.IsCurrentRowDirty && e.ColumnIndex > 0)
			{
				var currentRow = dgvArticles.Rows[e.RowIndex];
				float unit = 0;

				// Truong hop nhap unit ko phai la so
				if (!float.TryParse(currentRow.Cells[5].Value.ToString().Trim(), NumberStyles.Any, NumberFormatInfo.InvariantInfo, out unit))
				{
					MessageBox.Show("Unit must be a number in range 0..1", "Error",
					                MessageBoxButtons.OK, MessageBoxIcon.Error);
					e.Cancel = true;
				}
				// truong hop nhap so nhung vuot ra ngoai doan [0..1]
				else if (unit < 0 || unit > 1)
				{
					MessageBox.Show("Unit must be a number in range 0..1", "Error",
					                MessageBoxButtons.OK, MessageBoxIcon.Error);
					e.Cancel = true;
				}
				// Truong hop nhap du lieu ko day du
				else if (currentRow.Cells[2].Value == null || currentRow.Cells[3].Value == null ||
					string.IsNullOrEmpty(currentRow.Cells[2].Value.ToString()) ||
					string.IsNullOrEmpty(currentRow.Cells[3].Value.ToString()) ||
					currentRow.Cells[4].Value == null || currentRow.Cells[5].Value == null)
				{
					MessageBox.Show("You have to enter value for all cells", "Error",
					                MessageBoxButtons.OK, MessageBoxIcon.Error);
					e.Cancel = true;
				}
			}
			_currentRowDirty = dgvArticles.IsCurrentRowDirty;
		}

		/// <summary>
		/// Kiem tra trong market duoc chon da co mat hang trung ma hoac trung ten hay chua
		/// </summary>
		/// <param name="selectedArts">Danh sach mat hang duoc chon</param>
		/// <param name="marketId">Ma cua sieu thi duoc chon de copy toi</param>
		/// <returns>Tra ve danh sach mat hang khong bi trung ten va trung ma</returns>
		private List<Article> CheckForDuplicate(List<Article> selectedArts, int marketId)
		{
			// Lay danh sach mat hang cua sieu thi kia
			var otherArts = Article.Objects.Where(x => x.MarketId == marketId).ToList();

			// Lay danh sach ma mat hang va ten mat hang
			var codes = new HashSet<string>(otherArts.Select(x => x.ArtNo));
			var names = new HashSet<string>(otherArts.Select(x => x.ArtName));

			// Kiem tra trung
			var duplicate = selectedArts.Any(x => codes.Contains(x.ArtNo) || names.Contains(x.ArtName));

			// Thong bao cho nguoi dung biet bi trung
			if (duplicate)
			{
				var message = "There are some existing articles with same ART_NO or ART_NAME.\r\n" +
				              "Program will exclude the duplicate articles.\r\nDo you want to continue?";
				var msgResult = MessageBox.Show(message, "Warning !!!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
				if (msgResult == DialogResult.No)
					return new List<Article>();
			}
			return selectedArts.Where(x => !codes.Contains(x.ArtNo) && !names.Contains(x.ArtName)).ToList();
		}

        //Copy mặt hàng sang siêu thị khác
        private void btnCopy_Click(object sender, EventArgs e)
        {
            // Lay cac dong duoc chon, sau do lay ra cac mat hang
            var selectedArts = dgvArticles.Rows.Cast<DataGridViewRow>()
                .Where(x => x.Cells[0].Value != null && x.Cells[1].Value != null && (bool)x.Cells[0].Value)
                .Select(x => x.DataBoundItem as Article)
                .ToList();

            // Neu khong co mat hang nao duoc chon thi hien thong bao
            if (selectedArts.Count == 0)
            {
                MessageBox.Show("Please select article by checking on checkbox.", "Message",
                                MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            // Neu co thi bat hop thoai cho nguoi dung chon sieu thi
            var dlg = new MarketSelectorForm();
            if (dlg.ShowDialog() != DialogResult.OK) return;
            try
            {
                // Loai bo nhung mat hang trung ten hoac ma
                selectedArts = CheckForDuplicate(selectedArts, dlg.MarketId);
                if (selectedArts.Count == 0) return;

                // Tao ban sao cua cac mat hang do
                selectedArts = selectedArts.Select(x => new Article()
                {
                    ArtNo = x.ArtNo,
                    ArtName = x.ArtName,
                    MarketId = dlg.MarketId,
                    LastUpdated = DateTime.Now,
                    Cat = x.Cat,
                    Unit = x.Unit
                }).ToList();

                // Chen cac mat hang da chon vao CSDL
                Article.Objects.Insert(selectedArts);

                // Hien thong bao sao chep thanh cong
                MessageBox.Show("All selected articles is copied successful", "Message",
                                MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        //Xóa những mặt hàng đang chọn
        private void btnDelete_Click(object sender, EventArgs e)
        {
			// Lay nhung dong duoc danh dau check
			var selectedRows = dgvArticles.Rows.Cast<DataGridViewRow>()
					.Where(x => x.Cells[0].Value != null && x.Cells[1].Value != null && (bool)x.Cells[0].Value)
					.ToList();
			if (selectedRows.Count == 0)
			{
				MessageBox.Show("Please select article by checking on checkbox.", "Message",
								MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
				return;
			}

            var message = "All selected articles and related data will be deleted forever. Are you sure?";

            // Xuat thong bao yeu cau nguoi dung xac nhan viec xoa
            if (MessageBox.Show(message, "Warning !!!", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                // duyet qua tung dong duoc chon
                for (int i = selectedRows.Count - 1; i >= 0; i--)
                {
                    // Lay ra mat hang duoc chon
                    var art = selectedRows[i].DataBoundItem as Article;

                    // Goi ham xoa mat hang & xoa dong duoc chon
                    dgvArticles.Rows.Remove(selectedRows[i]);
                    WorkContext.Current.Articles.Delete(art);
                }
            }
        }

        //Sắp xếp các mặt hàng theo tên
        private void btnSort_Click(object sender, EventArgs e)
        {
            dgvArticles.DataSource = new BindingSource() {DataSource = WorkContext.Current.Articles.SortByName()};
        }

        private void dgvArticles_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void ArticleForm_Load(object sender, EventArgs e)
        {

        }
    }
}